/**
 * 操作键盘实现人物的运动漫游
 * 操作wasd和↑ ↓ ← →
 */
class KeyPathRoam {
    keyActions: any;
    cameraState: any;
    $viewer: any;
    moveSpeed: number
    turnSpeed: number;

    constructor(viewer: any,moveSpeed:number=1,turnSpeed:number=0.01) {
        this.$viewer = viewer;
        this.moveSpeed = moveSpeed;//上下移动速度
        this.turnSpeed = turnSpeed;//左右移动角度，【-180,180】
        this.keyActions = {
            ArrowUp: {moveForward: true},
            ArrowDown: {moveBackward: true},
            ArrowLeft: {turnLeft: true},
            ArrowRight: {turnRight: true},
            w: {moveForward: true},
            s: {moveBackward: true},
            a: {turnLeft: true},
            d: {turnRight: true},
            // 可以添加更多键及其对应操作
        };
        this.cameraState = {
            moveForward: false,
            moveBackward: false,
            turnLeft: false,
            turnRight: false,
        };
    }

    // key按下的事件
    handleKeyDown(event: any) {
        if (this.keyActions[event.key]) {
            Object.assign(this.cameraState, this.keyActions[event.key]);
        }
        this.updateCamera(this.$viewer);
    }

    // key抬起的事件
    handleKeyUp(event: any) {
        if (this.keyActions[event.key]) {
            Object.keys(this.keyActions[event.key]).forEach((action) => {
                this.cameraState[action] = false;
            });
            this.updateCamera(this.$viewer);
        }
    }

    //执行更新
    updateCamera(viewer: any) {
        //根据高度计算移动速度
        let cameraHeight = viewer.scene.globe.ellipsoid.cartesianToCartographic(viewer.camera.position).height;
        let moveRate = cameraHeight / 100.0;
        if (this.cameraState.moveForward) {
            viewer.scene.camera.moveForward(moveRate);
        }
        if (this.cameraState.moveBackward) {
            viewer.scene.camera.moveBackward(moveRate);
        }
        if (this.cameraState.turnLeft) {
            viewer.scene.camera.moveLeft(moveRate);
        }
        if (this.cameraState.turnRight) {
            viewer.scene.camera.moveRight(moveRate);
        }
    }
}

export default KeyPathRoam;
